package com.jswl.training.springjpa.service.impl;

import com.jswl.training.springjpa.dao.UserRepository;
import com.jswl.training.springjpa.entity.QClassRoom;
import com.jswl.training.springjpa.entity.QUser;
import com.jswl.training.springjpa.entity.User;
import com.jswl.training.springjpa.entity.vo.UserVo;
import com.jswl.training.springjpa.service.UserService;
import com.querydsl.core.BooleanBuilder;
import com.querydsl.core.QueryResults;
import com.querydsl.core.Tuple;
import com.querydsl.jpa.impl.JPAQueryFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    UserRepository userRepository;

    @Autowired
    JPAQueryFactory jpaQueryFactory;

    /**
     * 保存用户信息
     *
     * @param user
     */
    @Override
    public void saveUser(User user) {
        userRepository.save(user);
    }

    /**
     * 分页查询用户信息
     *
     * @param pageIndex 页码
     * @param pageSize  每页显示记录数
     * @return
     */
    @Override
    public Page<User> getPage(Integer pageIndex, Integer pageSize) {
        Sort sort =Sort.by(Sort.Direction.DESC,"id");
        Pageable pageable = PageRequest.of(pageIndex - 1, pageSize,sort);
        return userRepository.findAll(pageable);
    }

    /**
     * 根据用户昵称查找用户
     * @param userName
     * @return
     */
    @Override
    public List<User> findByUserName(String userName){
        return userRepository.findByUserName(userName);
    }


    @Override
    public List<User> getUsersBy(String userName){

        return userRepository.getUsersBy(userName);
    }

    /**
     * 测试QueryDSL
     * @param userName
     * @param phone
     * @return
     */
    @Override
    public List<User> getByUserNameAndPhone(String userName,String phone){
        QUser user=QUser.user;
//        List<User> users = jpaQueryFactory.selectFrom(user)
//                .where(user.userName.like("%" + userName + "%"),
//                        user.phone.eq(phone))
//                .orderBy(user.createTime.desc())
//                .offset(0)
//                .limit(10)
//                .fetch();

        //动态连接查询
        BooleanBuilder where = new BooleanBuilder();
        where.and(user.userName.like("%" + userName + "%"));
        where.and(user.phone.eq(phone));
        List<User> users = jpaQueryFactory.selectFrom(user)
                .where(where)
                .orderBy(user.createTime.desc())
                .offset(0)
                .limit(10)
                .fetch();


//        jpaQueryFactory.update(user).set(user.userName,"ceshi").where(user.id.eq(1L)).execute();
//        jpaQueryFactory.delete(user).where(user.id.eq(1L)).execute();


        return users;
    }


    @Override
    public Page<UserVo> getUserVoByUserName(String userName){
        Pageable pageable = PageRequest.of(1, 10);
        QUser user = QUser.user;
        QClassRoom classRoom = QClassRoom.classRoom;
        QueryResults<Tuple> query = jpaQueryFactory.select(user.id,user.userName,user.phone,user.age,classRoom.className)
                .from(user)
                .leftJoin(classRoom)
                .on(user.classId.eq(classRoom.id))
                .where(user.userName.like("%" + userName + "%"))
                .offset(pageable.getPageNumber()-1)
                .limit(10)
                .orderBy(user.id.desc())
                .fetchResults();
        List<UserVo> userVos = query.getResults().stream()
                //封装VO对象
                .map(tuple -> {
                    UserVo userVO = new UserVo();
                    userVO.setId(tuple.get(user.id));
                    userVO.setUserName(tuple.get(user.userName));
                    userVO.setAge(tuple.get(user.age));
                    userVO.setPhone(tuple.get(user.phone));
                    userVO.setClassName(tuple.get(classRoom.className));
                    return userVO;
                })
                .collect(Collectors.toList());
        return new PageImpl<UserVo>(userVos,pageable,query.getTotal());
    }

}
